package com.cloud.form.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloud.form.interfaces.FeignClientSystem;

/**
 * 文件上传工具类
 * 
 * @author taominglong
 *
 */
public class MediaStorageHelper {

	private static final Logger logger = LoggerFactory.getLogger(MediaStorageHelper.class);

	private static final String UPLOAD_URL = "media/api/storage/upload";
	private static final String DELETE_URL = "media/api/storage/delete";
	private static final String DOWNLOAD_URL = "media/api/storage/download";

	/**
	 * 文件上传
	 * 
	 * @param in
	 */
	public static boolean upload(InputStream in, String path) {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).build();
		HttpPost httpPost = new HttpPost(getMeidaServerPath() + UPLOAD_URL);
		if (logger.isDebugEnabled()) {
			logger.debug("文件上传url为 {}", getMeidaServerPath() + UPLOAD_URL);
		}
		httpPost.setConfig(requestConfig);
		MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
		multipartEntityBuilder.addBinaryBody("file", in, ContentType.MULTIPART_FORM_DATA, "");
		multipartEntityBuilder.addTextBody("path", path, ContentType.create("text/plain", Charset.forName("UTF-8")));
		HttpEntity httpEntity = multipartEntityBuilder.build();
		httpPost.setEntity(httpEntity);
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (logger.isDebugEnabled()) {
					logger.debug("文件上传成功，服务器返回信息：{}", httpResponse.getEntity().getContent().toString());
				}
				return true;
			} else {
				logger.error("文件上传失败，服务器返回信息：{}", httpResponse.getEntity().getContent().toString());
				return false;
			}
		} catch (IOException e) {
			throw new RuntimeException("文件上传失败", e);
		} finally {
			try {
				if (null != httpResponse) {
					httpResponse.close();
				}
				if (null != httpClient) {
					httpClient.close();
				}
			} catch (Exception e) {
				logger.error("关闭资源失败", e);
			}
		}
	}

	/**
	 * 文件删除
	 * 
	 * @param path
	 */
	public static boolean delete(String path) {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
		StringBuilder urlBuilder = new StringBuilder(getMeidaServerPath()).append(DELETE_URL).append("?path=")
				.append(path);
		HttpGet httpGet = new HttpGet(urlBuilder.toString());
		if (logger.isDebugEnabled()) {
			logger.debug("文件删除url为 {}", urlBuilder.toString());
		}
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (logger.isDebugEnabled()) {
					logger.debug("文件删除成功，服务器返回信息：{}", httpResponse.getEntity().getContent().toString());
				}
				return true;
			} else {
				logger.error("文件删除失败，服务器返回信息：{}", httpResponse.getEntity().getContent().toString());
				return false;
			}
		} catch (IOException e) {
			throw new RuntimeException("文件删除失败", e);
		} finally {
			try {
				if (null != httpResponse) {
					httpResponse.close();
				}
				if (null != httpClient) {
					httpClient.close();
				}
			} catch (Exception e) {
				logger.error("关闭资源失败", e);
			}
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param path
	 * @return
	 */
	public static InputStream download(String path) {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
		StringBuilder urlBuilder = new StringBuilder(getMeidaServerPath()).append(DOWNLOAD_URL).append("?path=")
				.append(path);
		HttpGet httpGet = new HttpGet(urlBuilder.toString());
		if (logger.isDebugEnabled()) {
			logger.debug("文件下载url为 {}", urlBuilder.toString());
		}
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				return httpResponse.getEntity().getContent();
			}
			throw new RuntimeException("文件下载失败，服务器返回信息：" + httpResponse.getEntity().getContent());
		} catch (IOException e) {
			throw new RuntimeException("文件下载失败", e);
		}
	}

	private static final String getMeidaServerPath() {
		FeignClientSystem feignClientSystem = SpringBeanHelper.getBean(FeignClientSystem.class);
		String mediaServerPath = feignClientSystem.getSysConfigItem("DEFAULT_MEDIA_SERVER_URL");
		if (StringUtils.isEmpty(mediaServerPath)) {
			logger.error("系统配置项< DEFAULT_MEDIA_SERVER_URL >未配置，采用默认值： http://127.0.0.1:9002/");
			mediaServerPath = "http://127.0.0.1:9002/";
		}
		return mediaServerPath;
	}
}
